# +----------------------------------------------------------------------
# | User: zq
# | Version: python3.7
# | Time: 2020-03-09 16:30
# +----------------------------------------------------------------------
from peewee import *

db = MySQLDatabase("spider", host="localhost", port=3306, user="root", password="root")

class Person(Model):
    name = CharField(max_length=20)
    birthday = DateField()

    class Meta:
        database = db # This model uses the "people.db" database
        table_name = "users" #可以自定义,如果不写,表名则为 person

#数据增加/删除/更新/查询



if __name__ == "__main__":
    db.create_tables([Person])

    #1. 新增数据
    # from datetime import date
    # uncle_bob = Person(name='Bob123', birthday=date(1960, 1, 15))
    # uncle_bob.save()  # bob is now stored in the database

    #2. 查询数据 获取1条,和获取多条
    # 获取1条
    # grandma = Person.select().where(Person.name == 'Bob').get()
    # 简化如下
    # try:
    #     grandma = Person.get(Person.name == 'Bob')
    #     print(grandma.birthday)
    # except Exception as e:
    #     print('Error:', e)
    # pass

    # #3. 查询数据, 获取多条
    # query = Person.select().where(Person.name == 'Bob')
    # for pet in query:
    #     print(pet.name, pet.birthday)
    # pass

    #4. 修改数据
    # query = Person.select().where(Person.name == 'Bob')
    # from datetime import date
    # for pet in query:
    #     pet.birthday = date(2021, 10, 12)
    #     pet.save() #在没有数据存在的时候新增数据,存在数据的时候修改数据
    # pass

    #5. 删除数据
    query = Person.select().where(Person.name == 'Bob')
    for pet in query:
        pet.delete_instance() #删除数据
    pass
